import { routerRedux } from 'dva/router';
import { parse, stringify } from 'qs';
import $api from '@/api';
import { setToken } from '@/utils/auth';
import { setAuthority } from '@/utils/authority';

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

export default {
  namespace: 'auth',
  state: {
    currentUser: {},
  },
  effects: {
    *login({ payload }, { call }) {
      const resp = yield call($api.auth.login, payload);
      if (resp.code === 0) {
        setToken(resp.data.accessToken);
        setAuthority(resp.data.codes);
      }
      return resp;
    },
    *getInfo(_, { call, put }) {
      const resp = yield call($api.auth.getInfo);
      if (resp.code === 0) {
        setAuthority(resp.data.codes);
      }
      yield put({
        type: 'saveCurrentUser',
        payload: resp.data,
      });
    },
    *logout(_, { put }) {
      const { redirect } = getPageQuery(); // redirect
      if (window.location.pathname !== '/auth/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/auth/login',
            search: stringify({
              redirect: window.location.href,
            }),
          }),
        );
      }
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },
  },
};
